package com.okoj.excel_lib_rary.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.DeleteObjectRequest;
import com.alibaba.sdk.android.oss.model.DeleteObjectResult;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.okoj.excel_lib_rary.R;
import com.okoj.excel_lib_rary.adapter.RemoteFileAdapter;
import com.okoj.excel_lib_rary.config.Config;
import com.okoj.excel_lib_rary.data.RemoteResp;
import com.okoj.excel_lib_rary.data.entity.RemoteFile;
import com.okoj.excel_lib_rary.data.entity.Result;
import com.okoj.excel_lib_rary.data.net.WpsClient;
import com.okoj.excel_lib_rary.listener.LoadDataListener;
import com.okoj.excel_lib_rary.oss.OssDownloadListener;
import com.okoj.excel_lib_rary.oss.OssManager;
import com.okoj.excel_lib_rary.util.WpsHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.okoj.excel_lib_rary.util.FileUtil.creteFilePath;
import static com.okoj.excel_lib_rary.util.FileUtil.getServerArgumentFileType;
import static com.okoj.excel_lib_rary.util.FileUtil.scan;

public class FileListActivity extends AppCompatActivity {

    private static final String TAG = FileListActivity.class.getSimpleName();

    public static void showFile(Context context) {
        Intent intent = new Intent(context, FileListActivity.class);
        context.startActivity(intent);
    }


    RecyclerView rvFile;

    QMUITipDialog loadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wps_activity_file_list);
        initDialog();
        findViewById(R.id.iv_back).setOnClickListener(v -> {
            onBackPressed();
        });
        rvFile = findViewById(R.id.rv_file);
        initRvFileAdapter();
        getRemoteFile();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destoryDialog();
    }

    RemoteFileAdapter remoteFileAdapter;

    private void initRvFileAdapter() {
        remoteFileAdapter = new RemoteFileAdapter(R.layout.wps_item_remote_file);
        rvFile.setLayoutManager(new LinearLayoutManager(this));
        rvFile.setAdapter(remoteFileAdapter);
        remoteFileAdapter.setOnItemClickListener((adapter, view, position) -> {
            RemoteFile item = remoteFileAdapter.getItem(position);
            try {
                EditActivity.editRemoteFile(this, item.getId().toString(),
                        getServerArgumentFileType(item.getDownload_url()));
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(FileListActivity.this, "文件名字异常", Toast.LENGTH_SHORT).show();
            }
        });
        remoteFileAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            showDeleteDialog(position);
            return true;
        });
        remoteFileAdapter.addChildClickViewIds(R.id.btn_download);
        remoteFileAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (WpsHelper.getBizCallBack() != null) {
                boolean canImport = WpsHelper.getBizCallBack().canImportFile();
                if (!canImport) {
                    return;
                }
            }

            int id = view.getId();
            RemoteFile item = remoteFileAdapter.getItem(position);
            if (id == R.id.btn_download) {
                download(item.getDownload_url(), item.getName());
            }
        });
    }

    private void getRemoteFile() {

        RemoteResp.getPersonFile(new LoadDataListener<List<RemoteFile>>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(List<RemoteFile> data) {
                List<RemoteFile> newdata = new ArrayList<>();
                if (data == null) {
                    return;
                }
                for (int i = 0; i < data.size(); i++) {
                    newdata.add(0, data.get(i));
                }
                remoteFileAdapter.setNewInstance(newdata);
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    private void showDeleteDialog(int pos) {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage("确定要删除文件吗？")
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction("确定", (dialog, index) -> {
                    dialog.dismiss();
                    deleteRemoteFile(pos);
                })
                .show();
    }

    private void deleteRemoteFile(final int position) {

        String fileId = remoteFileAdapter.getItem(position).getId().toString();
        Config config = WpsClient.getAppConfig();
        WpsClient.getInstance().wpsService().delete(config.getToken(),
                fileId,
                config.getAppid(),
                config.get_w_env(),
                config.get_w_platform())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Object o) {
                        remoteFileAdapter.remove(position);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 下载服务器上的文件
     *
     * @param objectKey
     */
    private void download(String objectKey, String fileName) {
        showLoadDialog();
        File target = creteFilePath(fileName, objectKey);
        OssManager.getInstance().downloadWps(target.getAbsolutePath(), objectKey, new OssDownloadListener() {
            @Override
            public void success(String filePath) {
                Log.i(TAG, "download success");
                scan(filePath, FileListActivity.this);
                runOnUiThread(() -> {
                    Toast.makeText(FileListActivity.this, "已经下载到本地", Toast.LENGTH_SHORT).show();
                    hideLoadDialog();
                });
            }

            @Override
            public void failure(String message) {
                Log.i(TAG, "download failure");
                runOnUiThread(() -> {
                    hideLoadDialog();
                    Toast.makeText(FileListActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
                });
            }
        });

    }

    private void initDialog() {
        loadingDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在加载")
                .create();
    }

    private void destoryDialog() {
        loadingDialog.cancel();
        loadingDialog = null;
    }

    private void showLoadDialog() {
        loadingDialog.show();
    }

    private void hideLoadDialog() {
        loadingDialog.dismiss();
    }


}
